import { View } from '@tarojs/components';
import CustomCarNumberInput from './custom-car-number-input';
import CustomKeyboard from './custom-keyboard';
import { useRef, useState, forwardRef, useImperativeHandle, useMemo } from 'react';
function CarPlateInput(props, ref) {
  const customKeyboardRef = useRef<any>(null);
  const customCarNumInputRef = useRef<any>(null);
  const [customCarNumInputIndex, setCustomCarNumInputIndex] = useState(0);
  const carNumber = useMemo(() => {
    return (customCarNumInputRef?.current?.numbers || []).map((item) => item.value).join('');
  }, [customCarNumInputRef?.current?.numbers]);

  const changeKeyboard = (type: any) => {
    if (customKeyboardRef?.current) {
      customKeyboardRef.current.change(type);
      customKeyboardRef.current.shows();
    }
  };

  const onInputFocus = (index) => {
    if (index == 0) {
      changeKeyboard(1);
    } else if (index == 7) {
      changeKeyboard(3);
    } else {
      changeKeyboard(2);
    }
    setCustomCarNumInputIndex(index);
  };

  const onKeyboardClick = (e: any) => {
    customCarNumInputRef.current.change({
      index: customCarNumInputIndex,
      value: e,
      remove: false,
    });
  };

  const onKeyboardDelete = () => {
    customCarNumInputRef.current.change({
      index: customCarNumInputIndex,
      value: '',
      remove: true,
    });
  };

  useImperativeHandle(ref, () => {
    return {
      carNumber,
    };
  });

  return (
    <View>
      <CustomCarNumberInput
        ref={customCarNumInputRef}
        bindfocus={onInputFocus}
      ></CustomCarNumberInput>
      <CustomKeyboard
        ref={customKeyboardRef}
        keyboardType={1}
        bindclick={onKeyboardClick}
        binddelete={onKeyboardDelete}
      ></CustomKeyboard>
    </View>
  );
}

export default forwardRef(CarPlateInput);
